/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package cn.lang.auth.oauth2;

import cn.hutool.json.JSONUtil;
import cn.lang.auth.common.utils.ret.CodeMsg;
import cn.lang.auth.common.utils.ret.Ret;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @title OAuth2Filter
* @description oauth2过滤器
* @author Lang 1102076808@qq.com
* @date 2020/6/19 21:27
*/
public class OAuth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) request);
        if(token==null||"".equals(token)){
            return null;
        }
        return new OAuth2Token(token);
    }

    /**
     * @Description:判断是否允许访问
     * @author: Lang
     * @Date: 2020/6/19 0:01
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if(token==null||"".equals(token)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpServletRequest httpRequest  =  (HttpServletRequest)request;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
            String json = JSONUtil.toJsonStr(Ret.error(CodeMsg.SERVER_AUTH_ERROR.fillArgs("token为空，非法访问！")));
            httpResponse.setCharacterEncoding("utf-8");
            httpResponse.setContentType("text/html; charset=UTF-8");
            httpResponse.getWriter().print(json);
            return false;
        }
        // <2> 执行登陆逻辑，实际执行的是基于 Token 进行认证。
        // 实际走的OAth2Realm种认证逻辑
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest  =  (HttpServletRequest)request;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("text/html; charset=UTF-8");
        try {
            //处理认证失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            String json = JSONUtil.toJsonStr(Ret.error(CodeMsg.SERVER_ERROR.fillArgs(throwable.getMessage())));
            httpResponse.getWriter().print(json);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("authorization");
        //如果header中不存在token，则从参数中获取token
        if(token==null){
            token = httpRequest.getParameter("authorization");
        }
        return token;
    }

}
